package com.cuit.jifver.weibo.net;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class SyncHttp
{
	private static final int TIME_OUT = 1000 * 6; // 超时
	private static final String METHOD_POST = "POST";
	private static final String METHOD_GET = "GET";
	private static final int HTTP_OK = 200;
	private final String CHARTSET = "UTF-8"; //字符编码
	private final int BUFFER = 1024 * 8;//缓冲区
	
	
	/**
	 * 通过GET方式发送请求
	 * @param url URL地址
	 * @param params 参数
	 * @return 
	 * @throws Exception
	 */
	public String httpGet(String url, String params) throws Exception
	{
		String response = null; //返回信息
		if (null!=params&&!params.equals(""))
		{
			url += "?" + params;
		}
		// 构造HttpClient的实例
		HttpClient httpClient = new DefaultHttpClient();
		// 创建GET方法的实例
		HttpGet httpGet = new HttpGet(url);
		try
		{
			HttpResponse httpResponse = httpClient.execute(httpGet);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) //SC_OK = 200
			{
				// 获得返回结果
				response = EntityUtils.toString(httpResponse.getEntity());
			}
			else
			{
				response =String.valueOf(statusCode);
			}
		} catch (Exception e)
		{
			throw new Exception(e);
		} 
		return response;
	}
	
	
	/**
	 * 模拟POST方式发送请求
	 * 
	 * @param urlStr
	 *            请求URL地址
	 * @param paramsStr
	 *            请求参数
	 * @return
	 * @throws Exception
	 */
	public String httpPost(String urlStr, String paramsStr) throws Exception
	{
		//把参数转换成字符数组
		byte[] data = paramsStr.getBytes();
		URL url = null;
		HttpURLConnection conn = null;
		InputStream inStream = null;
		String response = null;
		try
		{
			url = new URL(urlStr);
			//根据URL打开远程连接
			conn = (HttpURLConnection) url.openConnection();
			//设置参数
			conn.setConnectTimeout(TIME_OUT);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod(METHOD_POST);
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", CHARTSET);
			conn.setRequestProperty("Content-Length", String.valueOf(data.length));
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			//建立连接
			conn.connect();
			DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
			//把字节数组写到六种
			outputStream.write(data);
			//发送数据
			outputStream.flush();
			outputStream.close();
			//获取返回码
			int responseCode = conn.getResponseCode();
			if (responseCode == HTTP_OK)
			{
				//获取输入流
				inStream = conn.getInputStream();
				//从输入流中获取信息
				response = getResponse(inStream);
			}
			else
			{
				//请求失败
				response = "返回码："+responseCode;
			}
		} catch (Exception e)
		{
			throw e;
		}
		finally
		{
			//关闭连接
			conn.disconnect();
		}
		return response;
	}
	
	/**
	 * 获取输入流中信息
	 * @param inStream 输入流
	 * @return
	 * @throws IOException
	 */
	private String getResponse(InputStream inStream) throws IOException
	{
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		int len = -1;
		byte[] buffer = new byte[BUFFER];//缓冲区
		while((len=inStream.read(buffer))!=-1)
		{
			outputStream.write(buffer, 0, len);
		}
		byte[] data = outputStream.toByteArray();
		return new String(data);
	}

}
